package juc.task;
import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * 案例一 使用线程池+callable实现异步任务
 */

public class Task01 {

    public static void main(String[] args) {
        //创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //获取结果的集合
        ArrayList<Future<String>> list = new ArrayList<>();

        //提交任务
        for (int i = 0; i < 10; i++) {
            Future<String> future = executorService.submit(new Task01Callable(i));
            //将结果放入集合
            list.add(future);
        }

        //关闭线程池
        executorService.shutdown();

        //遍历结果
        for (Future<String> future : list) {
            try {
                //获取结果
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                executorService.shutdownNow();
                e.printStackTrace();
                return;
            }
        }
    }
}

//任务
class Task01Callable implements Callable<String> {
    private final int i;

    Task01Callable(int i) {
        this.i = i;
    }
    @Override
    public String call() throws Exception {
        return "当前是第" + i + "个任务";
    }
}


